package com.onepiece.dao;

import com.onepiece.metrics.CustomMetricsEnum;
import com.onepiece.metrics.MetricsService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;

/**
 * todo 注解应该不能继承的 不过测一下
 *
 * @author guoyanjiang
 */
@ComponentScan({"com.onepiece.metrics"})
public abstract class BaseDbMetricsAspect {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    MetricsService metricsService;

    @Value("${spring.datasource.dbName)")
    String dbName;

    public Object handleCache(ProceedingJoinPoint point) {
        return metricsService.record(CustomMetricsEnum.DB_LATENCY, () -> {
            try {
                return point.proceed();
            } catch (Throwable throwable) {
                logger.error("{} dao method {}", dbName, point.getSignature().getName());
                logger.error("读写 dao异常", throwable);
                metricsService.increment(CustomMetricsEnum.DB_EXCEPTION_TOTAL, "type", dbName);
                return null;
            }
        }, "type", dbName);
    }
}